package com.ihr360.authority.sharing.privilege;

import com.ihr360.authority.sharing.service.AuthUserResourceService;
import com.ihr360.commons.data.util.Pair;
import com.ihr360.commons.lang.CollectionUtils;
import com.ihr360.commons.request.Ihr360SearchBody;
import com.ihr360.commons.specification.Ihr360Predication;
import com.ihr360.commons.specification.Ihr360Specification;
import com.ihr360.commons.specification.PredicationOperator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class SearchPrivilege<ID> extends AbstractBizClassPrivilege<ID> {
    private  final static String ID="id";
    final Logger logger = LoggerFactory.getLogger(getClass());
    private Ihr360SearchBody searchBody;
    private boolean noData=false;
    public SearchPrivilege(AuthUserResourceService authUserResourceService, IAccessControlClass iAccessControlClass,Ihr360SearchBody searchBody) {
        super(iAccessControlClass);
        this.authUserResourceService = authUserResourceService;
        this.method = AccessControlMethod.METHODS.getAll;
        this.searchBody = searchBody;
    }


    public boolean isAccessControl() {
        return accessControl;
    }

    public boolean isNoData() {
        return noData;
    }

    public void validate() {
    }

    public SearchPrivilege doValidate() {
        boolean noAccessControl = noAccessControl(this.method);
        if (!noAccessControl) {
            Pair<Map<Object, Integer>, Map<Object, Integer>> pair =
                    authUserResourceService.queryUserResourcesPrivilege(iAccessControlClass.getEntityClass(), iAccessControlClass.getIdClass());
            if (pair != null) {
                toIDKeyMap(pair.getFirst(), pair.getSecond());
            }
            validate();
            if (searchBody.getSpecification() == null) {
                searchBody.setSpecification(new Ihr360Specification<>());
            }
            Ihr360Specification specification = (Ihr360Specification) searchBody.getSpecification();
            List<Ihr360Predication> predications = specification.getPredications();
            if (predications == null) {
                predications = new ArrayList<>();
                specification.setPredications(predications);
            }
            if (pair == null || pair.getFirst() == null
                    || CollectionUtils.isEmpty(userResourcesPrivilege)) {
                noData = true;
            }else{
                Set<Object> set = pair.getFirst().keySet();
                Ihr360Predication inPredication = new Ihr360Predication();
                inPredication.setFieldName(ID);
                inPredication.setOperator(PredicationOperator.IN);
                inPredication.setFieldValue(set);
                predications.add(0, inPredication);
            }

        }
        this.accessControl = !noAccessControl;
        return this;
    }
}